import cv2 as cv
import numpy as np

# New window
window_name = 'Chessboard'
window_size = (800, 600)
cv.namedWindow(window_name, cv.WINDOW_NORMAL)
cv.resizeWindow(window_name, window_size[0], window_size[1])


def on_trackbar_(val):
    rows = cv.getTrackbarPos('Rows', window_name)
    cols = cv.getTrackbarPos('Cols', window_name)
    size = cv.getTrackbarPos('Size', window_name)
    chessboard = create_chessboard(rows, cols, size)
    cv.imshow(window_name, chessboard)


def create_chessboard(rows, cols, size, background=255, foreground=0):
    width = (cols + 1) * size
    height = (rows + 1) * size
    new_chessboard = np.ones((height, width), np.float32)
    new_chessboard = new_chessboard * background
    block_fore_ground = np.ones((size, size), np.float32)
    block_fore_ground = block_fore_ground * foreground

    start_col = (width - (cols + 1) * size) // 2
    start_row = (height - (rows + 1) * size) // 2

    for c in range(0, cols, 2):
        for r in range(0, rows + 1, 2):
            # for c in range(0, cols * 2, 2):
            block_r = r * size + start_row
            block_c = c * size + start_col
            new_chessboard[block_r:block_r + size, block_c:block_c + size] = block_fore_ground
            if r < rows:
                block_r = (r + 1) * size + start_row
                block_c = (c + 1) * size + start_col
                new_chessboard[block_r:block_r + size, block_c:block_c + size] = block_fore_ground

    return new_chessboard


# Init. chessboard
# width, height = (480, 320)
# rows, cols = 6, 9
# size = 20
chessboard = create_chessboard(6, 9, 20)
# Gen. chessboard

cv.createTrackbar('Rows', window_name, 9, 100, on_trackbar_)
cv.createTrackbar('Cols', window_name, 6, 100, on_trackbar_)
cv.createTrackbar('Size', window_name, 6, 100, on_trackbar_)

cv.imshow(window_name, chessboard)

cv.waitKey(-1)
cv.destroyAllWindows()

